package io.gitee.cofenghen.jdbctempleplus.support;

import io.gitee.cofenghen.jdbctempleplus.model.SqlParameterSource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryCondition<T> {



    private List<Condition<T>> conditions = new ArrayList<>();
    public QueryCondition<T> add(Condition<T> condition) {
        conditions.add(condition);
        return this;
    }
    public List<Condition<T>> getConditions() {
        return conditions;
    }


    // 生成SQL片段
    public SqlParameterSource toSql() {
        StringBuilder sb=new StringBuilder();

        Map<String,Object>    params=new HashMap<>();
        var conditions=getConditions();
        Map<String, Integer> columnNameCount = new HashMap<>();
        for (var i=0;i<conditions.size();i++)
        {
            var condition =conditions.get(i);
            var  params_columnName=condition.getColumn();
            int count=0;
            if (i>0)
                sb.append(" and ");
            if (columnNameCount.containsKey(condition.getColumn()))
            {
                count= columnNameCount.get(condition.getColumn());
                columnNameCount.put(condition.getColumn(),count++);
                params_columnName= condition.getColumn()+"_"+count;
                sb.append(condition.getColumn()+" "+condition.getOperator().getSymbol()+" :"+params_columnName);
            }
            else
            {
                params_columnName= condition.getColumn();
                sb.append(condition.getColumn()+" "+condition.getOperator().getSymbol()+" :"+params_columnName);
                columnNameCount.put(condition.getColumn(),count);

            }
            params.put(params_columnName,condition.getValue());

        }
        return  new SqlParameterSource(sb.toString(), params);


    }


}
